package com.lzn.dds.dataSource;

import com.alibaba.druid.pool.DruidDataSource;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;

/**
 * 动态数据源管理器
 * @author lzn
 * @date 6/8/21 7:43 PM
 */
public class DDSHolder {
    private Map<String,DDSTimer> ddsMap = new HashMap<>();

    private static Timer clearIdleTask = new Timer();
    static{
        clearIdleTask.schedule(new ClearIdleTimerTask(),5000,60*1000);
    }
    private DDSHolder(){
    }
    // 获取单例对象
    public static DDSHolder instance(){
        return DDSHolderBuilder.instance;
    }
    public synchronized void addDDS(String projectCode, DruidDataSource dds){
        DDSTimer ddst = new DDSTimer(dds);
        ddsMap.put(projectCode,ddst);
    }

    public synchronized DruidDataSource getDDS(String projectCode){
        if(ddsMap.containsKey(projectCode)){
            DDSTimer ddst = ddsMap.get(projectCode);
            ddst.refreshTime();
            return ddst.getDds();
        }
        return null;
    }

    public synchronized void clearIdleDDS(){
        Iterator<Map.Entry<String,DDSTimer>> iter = ddsMap.entrySet().iterator();
        for( ;iter.hasNext(); ){
            Map.Entry<String,DDSTimer> entry = iter.next();
            if(entry.getValue().checkAndClose()){
                iter.remove();
            }
        }

    }

    private static class DDSHolderBuilder{
        private static DDSHolder instance = new DDSHolder();
    }
}
